package org.bdware.doip.core.model.digitalObject;

import com.google.gson.Gson;
import com.google.gson.JsonObject;

public class Element {
    /**
     * The id of the element.
     */
    public String id;

    /**
     * The size of the data portion.  May be -1 when the size is unknown.
     */
    public int length;

    /**
     * The type of the element.
     */
    public String type;

    /**
     * The attributes of the element.
     * {"api":true,url:""}这种类型，标识Element的值来自于一个restful接口
     */
    public JsonObject attributes;

    public String dataString;
    /**
     * The bytes of the element, as an {@code InputStream}.
     */
    private transient byte[] data;

    public Element(String id, String type){
        this.id = id;
        this.type = type;
        this.length = -1;
    }

    public void setData(byte[] data){
        if(data == null){
            this.data = null;
            this.length = 0;
            return;
        }
        this.data = data;
        this.length = data.length;
    }

    public void excludeData(){
        this.data = null;
    }

    public byte[] getData(){
        return data;
    }

    /**
     * A convenience method that sets an attribute on the object.
     *
     * @param name the name of the attribute
     * @param att the value to set as a String
     */
    public synchronized void setAttribute(String name, String att) {
        if (attributes == null) {
            attributes = new JsonObject();
        }
        attributes.addProperty(name, att);
    }

    public String toString(){
        return new Gson().toJson(this);
    }
}
